package com.zhsj.OkeHomeConsumption.ui.activity.wallet;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;


import com.google.gson.Gson;

import com.hjq.dialog.MessageDialog;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;


import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import butterknife.OnClick;

/**
 * Created by zwj on 2017/10/15.
 * 积分兑换
 */

public class RedeemFragment extends BaseFragment implements View.OnClickListener {


    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;

    //左标提
    private TextView topbar_textview_leftitle;
    //标题
    private TextView topbar_textview_title;
    private TextView topbar_textview_righttitle;

    private ClearEditText edit;
    private Button button;
    private FormalUserInfo userInfo;

    private TextView message_text;

    private TextView duihuan_text;

    private String fanhuan_price;

    public static RedeemFragment newInstance(String fanhuan_price) {

        Bundle args = new Bundle();
        RedeemFragment fragment = new RedeemFragment();
        args.putString("fanhuan_price", fanhuan_price);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fanhuan_price = getArguments().getString("fanhuan_price");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_redeem, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListener();
    }


    private void initView(View view) {
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("积分兑换");
        topbar_textview_righttitle = view.findViewById(R.id.topbar_textview_righttitle);
        topbar_textview_righttitle.setBackgroundResource(R.mipmap.gengduo);
        edit = view.findViewById(R.id.edit);
        button = view.findViewById(R.id.button_jifen);
        message_text = view.findViewById(R.id.message_text);
        duihuan_text = view.findViewById(R.id.duihuan_text);

                message_text.setText("当前可兑换积分"+fanhuan_price+"个");
        duihuan_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Gson gson = new Gson();
                Map<String, Object> mapjson = new HashMap<>();
                mapjson.put("integral", fanhuan_price);
                mapjson.put("userId", String.valueOf(userInfo.getId()));
                String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
                IsWalletUser(lifeCityCopartnerDTO);
            }
        });

    }



    private void initListener() {
        topbar_textview_leftitle.setOnClickListener(this);
        button.setOnClickListener(this);
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(_mActivity);
        topbar_textview_righttitle.setOnClickListener(this);
    }


    public void IsWalletUser(final String lifeCityCopartnerDTO) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);

        mSendCodeHashMap.put("lifeCityCopartnerDTO", lifeCityCopartnerDTO);

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.posttwo(OkeHomeConsumptionApi.ELVDOU_INTEGRALWITHDRAWAL, lifeCityCopartnerDTO, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        new MessageDialog.Builder(getActivity())
//                                .setTitle("提交申请") // 标题可以不用填写
                                .setMessage("兑换成功")
                                .setConfirm("去提现")
                                .setCancel("取消") // 设置 null 表示不显示取消按钮
                                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                                .setListener(new MessageDialog.OnListener() {

                                    @Override
                                    public void onConfirm(Dialog dialog) {
                                        startActivity(new Intent(getActivity(),MinewalletActivity.class));
                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onCancel(Dialog dialog) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override

            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }


    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
            case R.id.button_jifen:
                String text = edit.getText().toString().trim();
                if(text. equals("")){
                    showShortToast("请输入积分");
                    return;
                }
                Gson gson = new Gson();
                Map<String, Object> mapjson = new HashMap<>();
                mapjson.put("integral", text);
                mapjson.put("userId", String.valueOf(userInfo.getId()));
                String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
                IsWalletUser(lifeCityCopartnerDTO);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}
